package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.HashPromulgatorToReceiver;
import model.User;
import model.UserInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: a
 * Date: 2022-12-07
 * Time: 22:26
 */
class Message{
    public String message;
}

@WebServlet("/search")
public class Search extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    public static User user;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        //1. 获取到用户的登录状态
        HttpSession session = req.getSession(false);
        if(session == null){
            resp.setStatus(403);
            return;
        }
        User curUser = (User) session.getAttribute("user");
        if(curUser == null){
            resp.setStatus(403);
            return;
        }
        int curId = curUser.getUserid();
        HashPromulgatorToReceiver hashPromulgatorToReceiver = new HashPromulgatorToReceiver();

        //把body的json数据解析出来
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        System.out.println("进行了一次查找...");
        String title = message.message;
        if(title == null){
            resp.sendRedirect("microblog_search.html");
            return;
        }
        int id = Integer.parseInt(title);
        user = UserInfo.users[id];
        if(user == null){
            resp.sendRedirect("microblog_search.html");
            return;
        }
        if(hashPromulgatorToReceiver.find(curId, user)){
            user.isLive = 1;
        }else{
            user.isLive = 0;
        }
        resp.setContentType("application/json;charset=utf8");
        String jsonString = objectMapper.writeValueAsString(user);
        resp.getWriter().write(jsonString);
    }
}
